package top.chengdongqing.mishop.product.review.vo

import com.fasterxml.jackson.annotation.JsonFormat
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import top.chengdongqing.mishop.common.constants.DEFAULT_AVATAR_URL
import top.chengdongqing.mishop.entities.ProductReview
import top.chengdongqing.mishop.utils.DesensitizingUtils
import java.io.Serializable
import java.time.LocalDateTime

data class ProductReviewVO(
    val id: Int,
    val rating: Int,
    val content: String?,
    val photoUrls: List<String>?,
    val userName: String,
    val userAvatar: String,
    @JsonFormat(pattern = "yyyy-MM-dd")
    val createdAt: LocalDateTime
) : Serializable {
    companion object {
        fun of(review: ProductReview): ProductReviewVO {
            val user = review.user
            val userName = user?.let {
                user.name.takeIf { !review.isAnonymous || user.id == null }
                    ?: DesensitizingUtils.desensitizeNickname(user.name)
            } ?: "用户已注销"
            val userAvatarUrl = user?.avatarUrl.takeIf { !review.isAnonymous } ?: DEFAULT_AVATAR_URL

            return ProductReviewVO(
                review.id,
                review.rating,
                review.content,
                review.photoUrls?.let { jacksonObjectMapper().readValue(review.photoUrls!!) },
                userName,
                userAvatarUrl,
                review.createdAt!!
            )
        }
    }
}
